/* include ---------------------------------------------------------*/
#include "spi_card.h"
#include "lidar06.h"


/* private define -------------------------------------------------*/
#define File_Root 	"/sdcard"
#define TAG 		"SPI_SDCard"
#define SPI_DMA_CHAN 1
#define PIN_NUM_MISO 12
#define PIN_NUM_MOSI 13
#define PIN_NUM_CLK  14
#define PIN_NUM_CS   15

/* private variables ----------------------------------------------*/
QueueHandle_t SPI_Card_Queue = NULL;
//当前读写文件
char Create_File[] = "/sdcard/INFO.TXT";
FILE *myFile;


/* private function prototypes ------------------------------------*/


/* public variables -----------------------------------------------*/



/**
  * @brief  数据写入任务
  * @param  None
  * @retval None
  * @note   None
*/
void Card_WriteData_Task(void *pvParameters)
{
	//数据接收缓存区
	uint8_t sd_data[1024] = {0x00};

	while(1)
	{
		myFile = fopen(Create_File,"a");
		if (myFile == NULL) {
			ESP_LOGE(TAG, "Failed to open file for writing");
			goto failed;
		}
		memset(sd_data, 0, 1024);
		sprintf((char *)sd_data, "speed:%d,startA:%d,endA:%d,D1:%d,C1:%d,D2:%d,C2:%d,D3:%d,C3:%d,D4:%d,C4:%d,D5:%d,C5:%d,D6:%d,C6:%d,D7:%d,C7:%d,D8:%d,C8:%d,D9:%d,C9:%d,D10:%d,C10:%d.\n",
            LD06Class.LD_Data.speed, LD06Class.LD_Data.start_angle/100, LD06Class.LD_Data.end_angle/100,
			LD06Class.LD_Data.point[0].distance,LD06Class.LD_Data.point[0].confidence,LD06Class.LD_Data.point[1].distance,LD06Class.LD_Data.point[1].confidence,
            LD06Class.LD_Data.point[2].distance,LD06Class.LD_Data.point[2].confidence,LD06Class.LD_Data.point[3].distance,LD06Class.LD_Data.point[3].confidence,
            LD06Class.LD_Data.point[4].distance,LD06Class.LD_Data.point[4].confidence,LD06Class.LD_Data.point[5].distance,LD06Class.LD_Data.point[5].confidence,
            LD06Class.LD_Data.point[6].distance,LD06Class.LD_Data.point[6].confidence,LD06Class.LD_Data.point[7].distance,LD06Class.LD_Data.point[7].confidence,
            LD06Class.LD_Data.point[8].distance,LD06Class.LD_Data.point[8].confidence,LD06Class.LD_Data.point[9].distance,LD06Class.LD_Data.point[9].confidence);
	
		fwrite(sd_data, strlen((char *)sd_data), 1, myFile);
		fclose(myFile);
		failed:
		vTaskDelay(2000 / portTICK_PERIOD_MS);
	}

}

/**
  * @brief  SPI Card Init
  * @param  None
  * @retval None
  * @note   None
*/
void SPI_Card_Init(void)
{
	esp_err_t ret;
	esp_vfs_fat_mount_config_t mount_config = {
		.format_if_mount_failed = true,
		.max_files = 5,
		.allocation_unit_size = 16 * 1024
	};
	ESP_LOGI(TAG, "Initializing SD card");

	sdmmc_host_t host = SDSPI_HOST_DEFAULT();

	spi_bus_config_t spi_bus_cfg = {
		.mosi_io_num = PIN_NUM_MOSI,
        .miso_io_num = PIN_NUM_MISO,
        .sclk_io_num = PIN_NUM_CLK,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
        .max_transfer_sz = 4000,
    };
	ret = spi_bus_initialize(host.slot, &spi_bus_cfg, SPI_DMA_CHAN);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to initialize bus.");
        return ;
    }

	// 这将初始化没有卡检测（CD）和写保护（WP）信号的插槽。
    // 如果您的主板有这些信号，请修改slot_config.gpio_cd和slot_config.gpio_wp。
    sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT();
    slot_config.gpio_cs = PIN_NUM_CS;
    slot_config.host_id = host.slot;

	ESP_LOGI(TAG, "slot config success");

	sdmmc_card_t *card;

	//配置文件系统
	ret = esp_vfs_fat_sdspi_mount(File_Root, &host, &slot_config, &mount_config, &card);

	if (ret != ESP_OK) {
		if (ret == ESP_FAIL) {
			ESP_LOGE(TAG, "Failed to mount filesystem. "
						"If you want the card to be formatted, set the EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option.");
		} else {
			ESP_LOGE(TAG, "Failed to initialize the card (%s). "
						"Make sure SD card lines have pull-up resistors in place.", esp_err_to_name(ret));
		}
		return;
	}
	ESP_LOGI(TAG, "Filesystem mounted");

	// Card has been initialized, print its properties
	sdmmc_card_print_info(stdout, card);

	myFile = fopen(Create_File,"w");

	if (myFile == NULL) {
		ESP_LOGE(TAG, "Failed to open file for writing");
		return;
	}

	fwrite("xxx:", 4, 1, myFile);

	fclose(myFile);
	//输出SD名称
	// fprintf(f, "Hello %s!\n", card->cid.name);

	//创建消息写入任务
	xTaskCreatePinnedToCore(Card_WriteData_Task,"Card_WriteData_Task",8192,NULL,19,NULL,1);
}


